package lotus.blog.lotusblog.controller;

import lotus.blog.lotusblog.mapper.UserMapper;
import lotus.blog.lotusblog.pojo.User;
import lotus.blog.lotusblog.utils.ResultTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/image")
public class ImageController {
    String path = "D:\\.all-project\\blog_project";//"/home/Lotus/static-source"
    @Autowired
    UserMapper userMapper;
    @PostMapping("/upload")
    public ResultTemplate upload(MultipartFile file){
        //获取上传图片的地址
        //保存图片的路径
        String filePath = path;
        //获取图片的扩展名
        String Filename = file.getOriginalFilename();
        String suffixName = file.getSize()+Filename.substring(Filename.lastIndexOf("."));  // 后缀名
        //新的文件的名字
        String newFileName = file.getSize()+System.currentTimeMillis() + suffixName; // 新文件名
        //封装上传文件的全路径
        File targetFile = new File(filePath ,newFileName);
        //把本地文件上传到封装上传文件位置的全路径
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fullPath = "https://www.nanotus.cn/static/"+newFileName;
        return ResultTemplate.succ("上传成功",fullPath);
    }

    @PostMapping("/uploadAvatar")
    public ResultTemplate uploadAvatar(MultipartFile file,@RequestParam("username")String username){
        ResultTemplate upload = this.upload(file);
        if(upload.getCode().equals("0")){
            try{
                User userByUsername = userMapper.getUserByUsername(username);
                String oldAvatar = userByUsername.getAvatar();
                userByUsername.setAvatar((String) upload.getData());
                userMapper.updateById(userByUsername);
                String deletePath = path+"\\"+oldAvatar.replace("https://www.nanotus.cn/static/","");
                System.out.println(deletePath);
                File deleteFile = new File(deletePath);
                if(deleteFile.exists()) {
                    deleteFile.delete();
                }
            }catch (Exception e){
                ResultTemplate.fail("上传失败");

            }

        }else{
            ResultTemplate.fail("上传失败");
        }
        return ResultTemplate.succ("上传成功",upload.getData());
    }
}
